package com.riant.day09;
import	java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.BlockingQueue;
import	java.util.concurrent.locks.ReentrantLock;
import java.util.Arrays;
import	java.util.concurrent.locks.Condition;

import java.util.concurrent.locks.Lock;

/**
 * @Classname Bank
 * @Description TODO
 * @Date 2021/3/30 15:05
 * @Created by 张斌
 */
public class Bank {
    private double[] accounts;
    private Lock lock;
    private Condition condition;
    private BlockingQueue blockingQueue=new LinkedBlockingQueue();

    public Bank(int n,double initialBalance) {
        accounts = new double[n];
        Arrays.fill(accounts,initialBalance);
        lock=new ReentrantLock();//可重入锁
        condition=lock.newCondition();
    }

    public void tranfer(int from, int to, double amount){
        lock.lock();
        try {
            while (accounts[from]<amount){
                condition.await();
            }
            System.out.print(Thread.currentThread().getName());
            accounts[from] -= amount;
            accounts[to]+=amount;
            System.out.printf(" %10.2f from %d to %d ,",amount,from,to);
            System.out.printf("Total Balance: %10.2f%n",getTotalBalance());
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public double getTotalBalance(){
        double sum =0;
        for(double item:accounts){
            sum+=item;
        }
        return sum;
    }

    public int getSize(){
        return accounts.length;
    }
}
